import React, { useState, useEffect } from 'react';
import Sidebar from '../../components/sidebar';
import defaultAvatar from '../../static/defaultAvatar.png';

const Claims = () => {
    // 状态管理
    const [activeTab, setActiveTab] = useState('recommendations');
    const [preferences, setPreferences] = useState(null);
    const [recommendations, setRecommendations] = useState([]);
    const [applications, setApplications] = useState([]);
    const [plantClaims, setPlantClaims] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showPreferenceForm, setShowPreferenceForm] = useState(false);
    const [newApplication, setNewApplication] = useState({
        plant_id: '',
        reason: '',
        care_plan: '',
        is_collaborative: false,
        tags: []
    });
    const [applicationStatusFilter, setApplicationStatusFilter] = useState('all');
    const [currentApplication, setCurrentApplication] = useState(null);
    const [showApplicationDetail, setShowApplicationDetail] = useState(false);
    const [careNotes, setCareNotes] = useState('');

    // 偏好设置表单状态
    const [preferenceForm, setPreferenceForm] = useState({
        preferred_plant_types: [],
        preferred_locations: [],
        care_frequency: '',
        max_plants: 3,
        notification_preferences: {
            email: true,
            push: true
        }
    });

    // 模拟数据
    const mockPreferences = {
        preferred_plant_types: ['多肉', '绿萝', '仙人掌'],
        preferred_locations: ['阳台', '客厅'],
        care_frequency: 'weekly',
        max_plants: 3,
        notification_preferences: {
            email: true,
            push: true
        }
    };

    const mockRecommendations = [
        {
            id: 'plant-001',
            name: '多肉植物',
            location: '阳光房',
            types: ['多肉', '耐旱'],
            care_frequency: 'weekly'
        },
        {
            id: 'plant-002',
            name: '绿萝',
            location: '客厅角落',
            types: ['观叶', '喜阴'],
            care_frequency: 'biweekly'
        },
        {
            id: 'plant-003',
            name: '仙人掌',
            location: '阳台',
            types: ['多肉', '耐旱', '喜光'],
            care_frequency: 'monthly'
        },
        {
            id: 'plant-004',
            name: '富贵竹',
            location: '书房',
            types: ['观叶', '水培'],
            care_frequency: 'weekly'
        },
        {
            id: 'plant-005',
            name: '龟背竹',
            location: '客厅',
            types: ['观叶', '大型'],
            care_frequency: 'biweekly'
        },
        {
            id: 'plant-006',
            name: '虎皮兰',
            location: '卧室',
            types: ['观叶', '净化空气'],
            care_frequency: 'monthly'
        }
    ];

    const mockApplications = [
        {
            id: 'app-001',
            plant_id: 'plant-002',
            reason: '我有丰富的绿萝养护经验，家里也有类似的植物，能够很好地照顾它。',
            care_plan: '每周浇水一次，保持土壤湿润但不积水，定期擦拭叶片保持清洁。',
            status: 'pending',
            created_at: '2025-06-15T09:30:00',
            tags: ['经验丰富', '室内'],
            is_collaborative: false
        },
        {
            id: 'app-002',
            plant_id: 'plant-005',
            reason: '喜欢大型观叶植物，家里空间足够，能够提供良好的生长环境。',
            care_plan: '每两周浇水一次，避免阳光直射，定期施肥。',
            status: 'approved',
            created_at: '2025-06-10T14:20:00',
            tags: ['大型植物', '有空间'],
            is_collaborative: true,
            review_notes: '申请通过，请注意保持适当湿度。'
        },
        {
            id: 'app-003',
            plant_id: 'plant-001',
            reason: '非常喜欢多肉植物，已经养了很多品种。',
            care_plan: '每周浇水一次，保证充足阳光，控制温度。',
            status: 'rejected',
            created_at: '2025-06-05T11:45:00',
            tags: ['多肉爱好者'],
            is_collaborative: false,
            review_notes: '很遗憾，该植物已被他人认领。'
        }
    ];

    const mockPlantClaims = [
        {
            plant_id: 'plant-005',
            plant_name: '龟背竹',
            claimed_at: '2025-06-12T00:00:00',
            care_notes: '生长状况良好，新叶已长出。',
            collaborators: [
                { id: 'user-001', name: '张三' },
                { id: 'user-002', name: '李四' }
            ]
        },
        {
            plant_id: 'plant-006',
            plant_name: '虎皮兰',
            claimed_at: '2025-05-28T00:00:00',
            care_notes: '耐旱，生长缓慢，状态稳定。',
            collaborators: []
        }
    ];

    // 加载所有假数据
    useEffect(() => {
        // 模拟加载延迟
        setTimeout(() => {
            try {
                // 设置假数据
                setPreferences(mockPreferences);
                setPreferenceForm(mockPreferences);
                setRecommendations(mockRecommendations);
                setApplications(mockApplications);
                setPlantClaims(mockPlantClaims);
                setError(null);
            } catch (err) {
                console.error('Error loading mock data:', err);
                setError('加载数据失败，请刷新页面重试');
            } finally {
                setLoading(false);
            }
        }, 800); // 模拟网络延迟
    }, []);

    // 保存偏好设置（仅本地）
    const handleSavePreferences = (e) => {
        e.preventDefault();
        setLoading(true);

        // 模拟保存延迟
        setTimeout(() => {
            try {
                setPreferences(preferenceForm);
                setShowPreferenceForm(false);
                setError(null);
            } catch (err) {
                console.error('Error saving preferences:', err);
                setError('保存偏好设置失败，请重试');
            } finally {
                setLoading(false);
            }
        }, 500);
    };

    // 提交认领申请（仅本地）
    const handleSubmitApplication = (e) => {
        e.preventDefault();
        setLoading(true);

        // 模拟提交延迟
        setTimeout(() => {
            try {
                // 创建新申请对象
                const application = {
                    id: `app-${Date.now().toString().slice(-4)}`,
                    ...newApplication,
                    status: 'pending',
                    created_at: new Date().toISOString()
                };

                // 添加到本地列表
                setApplications([application, ...applications]);

                // 重置表单
                setNewApplication({
                    plant_id: '',
                    reason: '',
                    care_plan: '',
                    is_collaborative: false,
                    tags: []
                });

                setError(null);
                // 切换到申请列表
                setActiveTab('applications');
            } catch (err) {
                console.error('Error submitting application:', err);
                setError('提交申请失败，请重试');
            } finally {
                setLoading(false);
            }
        }, 500);
    };

    // 取消认领申请（仅本地）
    const handleCancelApplication = (applicationId) => {
        if (window.confirm('确定要取消此申请吗？此操作不可恢复。')) {
            setLoading(true);

            // 模拟操作延迟
            setTimeout(() => {
                try {
                    setApplications(applications.filter(app => app.id !== applicationId));
                    setError(null);
                } catch (err) {
                    console.error('Error canceling application:', err);
                    setError('取消申请失败，请重试');
                } finally {
                    setLoading(false);
                }
            }, 500);
        }
    };

    // 查看申请详情（仅本地）
    const handleViewApplication = (applicationId) => {
        setLoading(true);

        // 模拟加载延迟
        setTimeout(() => {
            try {
                const app = applications.find(app => app.id === applicationId);
                setCurrentApplication(app);
                setShowApplicationDetail(true);
                setError(null);
            } catch (err) {
                console.error('Error fetching application details:', err);
                setError('获取申请详情失败，请重试');
            } finally {
                setLoading(false);
            }
        }, 300);
    };

    // 更新养护记录（仅本地）
    const handleUpdateCareNotes = (plantId) => {
        setLoading(true);

        // 模拟更新延迟
        setTimeout(() => {
            try {
                setPlantClaims(plantClaims.map(claim =>
                    claim.plant_id === plantId ? { ...claim, care_notes: careNotes } : claim
                ));
                setCareNotes('');
                setError(null);
            } catch (err) {
                console.error('Error updating care notes:', err);
                setError('更新养护记录失败，请重试');
            } finally {
                setLoading(false);
            }
        }, 300);
    };

    // 释放认领植物（仅本地）
    const handleReleaseClaim = (plantId) => {
        if (window.confirm('确定要释放此认领的植物吗？此操作不可恢复。')) {
            setLoading(true);

            // 模拟操作延迟
            setTimeout(() => {
                try {
                    setPlantClaims(plantClaims.filter(claim => claim.plant_id !== plantId));
                    setError(null);
                } catch (err) {
                    console.error('Error releasing claim:', err);
                    setError('释放认领失败，请重试');
                } finally {
                    setLoading(false);
                }
            }, 500);
        }
    };

    // 筛选申请
    const filteredApplications = applicationStatusFilter === 'all'
        ? applications
        : applications.filter(app => app.status === applicationStatusFilter);

    // 状态标签样式
    const getStatusBadge = (status) => {
        const styles = {
            pending: 'bg-yellow-100 text-yellow-800',
            approved: 'bg-green-100 text-green-800',
            rejected: 'bg-red-100 text-red-800',
            expired: 'bg-gray-100 text-gray-800'
        };

        const labels = {
            pending: '待审核',
            approved: '已通过',
            rejected: '已拒绝',
            expired: '已过期'
        };

        return (
            <span className={`px-2 py-1 text-xs rounded-full ${styles[status] || 'bg-gray-100 text-gray-800'}`}>
                {labels[status] || status}
            </span>
        );
    };

    // 加载状态组件
    const LoadingIndicator = () => (
        <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-green-500"></div>
        </div>
    );

    // 错误提示组件
    const ErrorAlert = () => (
        error && (
            <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4 flex items-center">
                <span>{error}</span>
            </div>
        )
    );

    // 偏好设置表单
    const PreferenceForm = () => (
        <div className="bg-white p-6 rounded-lg shadow-md">
            <h3 className="text-lg font-semibold mb-4">
                {preferences ? '更新偏好设置' : '设置您的认领偏好'}
            </h3>
            <form onSubmit={handleSavePreferences}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            偏好植物类型 (用逗号分隔)
                        </label>
                        <input
                            type="text"
                            value={preferenceForm.preferred_plant_types.join(',')}
                            onChange={(e) => setPreferenceForm({
                                ...preferenceForm,
                                preferred_plant_types: e.target.value.split(',').map(t => t.trim()).filter(Boolean)
                            })}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md"
                            placeholder="例如：多肉, 绿萝, 仙人掌"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            偏好位置 (用逗号分隔)
                        </label>
                        <input
                            type="text"
                            value={preferenceForm.preferred_locations.join(',')}
                            onChange={(e) => setPreferenceForm({
                                ...preferenceForm,
                                preferred_locations: e.target.value.split(',').map(l => l.trim()).filter(Boolean)
                            })}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md"
                            placeholder="例如：阳台, 客厅, 办公室"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            期望养护频率
                        </label>
                        <select
                            value={preferenceForm.care_frequency}
                            onChange={(e) => setPreferenceForm({
                                ...preferenceForm,
                                care_frequency: e.target.value
                            })}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md"
                            required
                        >
                            <option value="">选择频率</option>
                            <option value="daily">每天</option>
                            <option value="weekly">每周</option>
                            <option value="biweekly">每两周</option>
                            <option value="monthly">每月</option>
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            最大认领数量
                        </label>
                        <input
                            type="number"
                            min="1"
                            max="10"
                            value={preferenceForm.max_plants}
                            onChange={(e) => setPreferenceForm({
                                ...preferenceForm,
                                max_plants: parseInt(e.target.value)
                            })}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md"
                            required
                        />
                    </div>
                </div>

                <div className="mb-4">
                    <h4 className="text-sm font-medium text-gray-700 mb-2">通知偏好</h4>
                    <div className="flex items-center space-x-4">
                        <label className="flex items-center">
                            <input
                                type="checkbox"
                                checked={preferenceForm.notification_preferences.email}
                                onChange={(e) => setPreferenceForm({
                                    ...preferenceForm,
                                    notification_preferences: {
                                        ...preferenceForm.notification_preferences,
                                        email: e.target.checked
                                    }
                                })}
                                className="mr-2"
                            />
                            邮件通知
                        </label>
                        <label className="flex items-center">
                            <input
                                type="checkbox"
                                checked={preferenceForm.notification_preferences.push}
                                onChange={(e) => setPreferenceForm({
                                    ...preferenceForm,
                                    notification_preferences: {
                                        ...preferenceForm.notification_preferences,
                                        push: e.target.checked
                                    }
                                })}
                                className="mr-2"
                            />
                            推送通知
                        </label>
                    </div>
                </div>

                <div className="flex justify-end space-x-3">
                    {preferences && (
                        <button
                            type="button"
                            onClick={() => setShowPreferenceForm(false)}
                            className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50"
                        >
                            取消
                        </button>
                    )}
                    <button
                        type="submit"
                        disabled={loading}
                        className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-green-300"
                    >
                        {loading ? '保存中...' : '保存偏好'}
                    </button>
                </div>
            </form>
        </div>
    );

    // 认领申请表单
    const ApplicationForm = () => (
        <div className="bg-white p-6 rounded-lg shadow-md">
            <h3 className="text-lg font-semibold mb-4">提交认领申请</h3>
            <form onSubmit={handleSubmitApplication}>
                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        植物ID
                    </label>
                    <input
                        type="text"
                        value={newApplication.plant_id}
                        onChange={(e) => setNewApplication({
                            ...newApplication,
                            plant_id: e.target.value
                        })}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md"
                        placeholder="输入要认领的植物ID"
                        required
                    />
                </div>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        认领理由
                    </label>
                    <textarea
                        value={newApplication.reason}
                        onChange={(e) => setNewApplication({
                            ...newApplication,
                            reason: e.target.value
                        })}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md"
                        rows="3"
                        placeholder="说明您想认领这株植物的原因"
                        maxLength="1000"
                        required
                    ></textarea>
                </div>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        养护计划
                    </label>
                    <textarea
                        value={newApplication.care_plan}
                        onChange={(e) => setNewApplication({
                            ...newApplication,
                            care_plan: e.target.value
                        })}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md"
                        rows="3"
                        placeholder="您计划如何养护这株植物"
                        maxLength="1000"
                        required
                    ></textarea>
                </div>

                <div className="mb-4">
                    <label className="flex items-center">
                        <input
                            type="checkbox"
                            checked={newApplication.is_collaborative}
                            onChange={(e) => setNewApplication({
                                ...newApplication,
                                is_collaborative: e.target.checked
                            })}
                            className="mr-2"
                        />
                        协作认领（可邀请其他用户共同养护）
                    </label>
                </div>

                <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                        标签 (用逗号分隔)
                    </label>
                    <input
                        type="text"
                        value={newApplication.tags.join(',')}
                        onChange={(e) => setNewApplication({
                            ...newApplication,
                            tags: e.target.value.split(',').map(t => t.trim()).filter(Boolean)
                        })}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md"
                        placeholder="例如：新手, 室内, 喜光"
                    />
                </div>

                <div className="flex justify-end">
                    <button
                        type="submit"
                        disabled={loading}
                        className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-green-300"
                    >
                        {loading ? '提交中...' : '提交申请'}
                    </button>
                </div>
            </form>
        </div>
    );

    // 申请详情弹窗
    const ApplicationDetailModal = () => (
        currentApplication && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                <div className="bg-white rounded-lg shadow-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                    <div className="p-6 border-b">
                        <div className="flex justify-between items-center">
                            <h3 className="text-xl font-semibold">申请详情</h3>
                            <button
                                onClick={() => setShowApplicationDetail(false)}
                                className="text-gray-500 hover:text-gray-700"
                            >
                                <X size={20} />
                            </button>
                        </div>
                    </div>

                    <div className="p-6">
                        <div className="flex justify-between items-start mb-4">
                            <div>
                                <p className="text-sm text-gray-500">植物ID</p>
                                <p className="font-medium">{currentApplication.plant_id}</p>
                            </div>
                            {getStatusBadge(currentApplication.status)}
                        </div>

                        <div className="mb-4">
                            <p className="text-sm text-gray-500 mb-1">认领理由</p>
                            <p className="whitespace-pre-line bg-gray-50 p-3 rounded-md">{currentApplication.reason}</p>
                        </div>

                        <div className="mb-4">
                            <p className="text-sm text-gray-500 mb-1">养护计划</p>
                            <p className="whitespace-pre-line bg-gray-50 p-3 rounded-md">{currentApplication.care_plan}</p>
                        </div>

                        <div className="mb-4">
                            <p className="text-sm text-gray-500 mb-1">申请时间</p>
                            <p>{new Date(currentApplication.created_at).toLocaleString()}</p>
                        </div>

                        {currentApplication.tags && currentApplication.tags.length > 0 && (
                            <div className="mb-4">
                                <p className="text-sm text-gray-500 mb-1">标签</p>
                                <div className="flex flex-wrap gap-2">
                                    {currentApplication.tags.map((tag, index) => (
                                        <span key={index} className="px-2 py-1 bg-gray-100 text-gray-800 rounded-full text-xs">
                                            {tag}
                                        </span>
                                    ))}
                                </div>
                            </div>
                        )}

                        {currentApplication.review_notes && (
                            <div className="mb-4">
                                <p className="text-sm text-gray-500 mb-1">审核意见</p>
                                <p className="bg-gray-50 p-3 rounded-md">{currentApplication.review_notes}</p>
                            </div>
                        )}

                        {currentApplication.is_collaborative && (
                            <div className="mb-4">
                                <div className="flex justify-between items-center mb-2">
                                    <p className="text-sm text-gray-500">协作人</p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-md">
                                    <p className="text-sm text-gray-500">暂无协作人</p>
                                </div>
                            </div>
                        )}
                    </div>

                    <div className="p-4 border-t flex justify-end space-x-3">
                        {currentApplication.status === 'pending' && (
                            <>
                                <button
                                    onClick={() => {/* 编辑申请的逻辑 */ }}
                                    className="px-3 py-1 border border-gray-300 rounded-md text-sm hover:bg-gray-50"
                                >
                                </button>
                                <button
                                    onClick={() => {
                                        handleCancelApplication(currentApplication.id);
                                        setShowApplicationDetail(false);
                                    }}
                                    className="px-3 py-1 border border-red-300 text-red-600 rounded-md text-sm hover:bg-red-50"
                                >
                                    取消申请
                                </button>
                            </>
                        )}
                        <button
                            onClick={() => setShowApplicationDetail(false)}
                            className="px-4 py-1 bg-gray-100 rounded-md text-sm hover:bg-gray-200"
                        >
                            关闭
                        </button>
                    </div>
                </div>
            </div>
        )
    );

    return (
        <div className="flex h-screen overflow-hidden">
            <Sidebar />
            <div className="flex-1 flex flex-col overflow-hidden">
                <header className="flex justify-between items-center p-4 bg-white shadow">
                    <h1 className="text-xl font-semibold">植物管理</h1>
                    <div className="flex items-center">
                        <span className="mr-2">用户名</span>
                        <img className='w-10 h-10 rounded-full border-black border-2' src={defaultAvatar} alt="用户头像" />
                    </div>
                </header>

                <main className="flex-1 overflow-y-auto bg-gray-50 p-6">
                    <ErrorAlert />

                    {/* 标签导航 */}
                    <div className="mb-6 border-b border-gray-200">
                        <div className="flex space-x-8">
                            <button
                                onClick={() => setActiveTab('recommendations')}
                                className={`py-4 text-sm font-medium border-b-2 ${activeTab === 'recommendations'
                                    ? 'text-green-600 border-green-500'
                                    : 'text-gray-500 hover:text-gray-700 border-transparent hover:border-gray-300'
                                    }`}
                            >
                                推荐植物
                            </button>
                            <button
                                onClick={() => setActiveTab('applications')}
                                className={`py-4 text-sm font-medium border-b-2 ${activeTab === 'applications'
                                    ? 'text-green-600 border-green-500'
                                    : 'text-gray-500 hover:text-gray-700 border-transparent hover:border-gray-300'
                                    }`}
                            >
                                我的申请
                                {applications.length > 0 && (
                                    <span className="ml-2 bg-gray-100 text-gray-800 text-xs px-2 py-0.5 rounded-full">
                                        {applications.length}
                                    </span>
                                )}
                            </button>
                            <button
                                onClick={() => setActiveTab('myClaims')}
                                className={`py-4 text-sm font-medium border-b-2 ${activeTab === 'myClaims'
                                    ? 'text-green-600 border-green-500'
                                    : 'text-gray-500 hover:text-gray-700 border-transparent hover:border-gray-300'
                                    }`}
                            >
                                我的认领
                                {plantClaims.length > 0 && (
                                    <span className="ml-2 bg-gray-100 text-gray-800 text-xs px-2 py-0.5 rounded-full">
                                        {plantClaims.length}
                                    </span>
                                )}
                            </button>
                            <button
                                onClick={() => setActiveTab('preferences')}
                                className={`py-4 text-sm font-medium border-b-2 ${activeTab === 'preferences'
                                    ? 'text-green-600 border-green-500'
                                    : 'text-gray-500 hover:text-gray-700 border-transparent hover:border-gray-300'
                                    }`}
                            >
                                偏好设置
                            </button>
                        </div>
                    </div>

                    {/* 内容区域 */}
                    {loading ? (
                        <LoadingIndicator />
                    ) : (
                        <>
                            {/* 推荐植物标签页 */}
                            {activeTab === 'recommendations' && (
                                <div>
                                    <div className="flex justify-between items-center mb-6">
                                        <h2 className="text-lg font-semibold">为您推荐的植物</h2>
                                        <button
                                            onClick={() => setActiveTab('newApplication')}
                                            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                                        >
                                            提交认领申请
                                        </button>
                                    </div>

                                    {recommendations.length === 0 ? (
                                        <div className="bg-white p-8 rounded-lg shadow text-center">
                                            <h3 className="text-lg font-medium text-gray-900 mb-2">暂无推荐植物</h3>
                                            <p className="text-gray-500 mb-4">完善您的偏好设置可以获得更精准的推荐</p>
                                            <button
                                                onClick={() => {
                                                    setActiveTab('preferences');
                                                    setShowPreferenceForm(true);
                                                }}
                                                className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                                            >
                                                设置偏好
                                            </button>
                                        </div>
                                    ) : (
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                            {recommendations.map((plant) => (
                                                <div key={plant.id} className="bg-white rounded-lg shadow overflow-hidden">
                                                    <div className="h-48 bg-gray-200 relative">
                                                        {/* 植物图片占位 */}
                                                        <div className="absolute inset-0 flex items-center justify-center">
                                                        </div>
                                                        <div className="absolute top-2 right-2 bg-green-100 text-green-800 text-xs px-2 py-1 rounded">
                                                            可认领
                                                        </div>
                                                    </div>
                                                    <div className="p-4">
                                                        <h3 className="font-semibold text-lg mb-1">{plant.name || `植物 ${plant.id.slice(0, 8)}`}</h3>
                                                        <p className="text-sm text-gray-500 mb-3">{plant.location || '未知位置'}</p>

                                                        <div className="mb-3">
                                                            <p className="text-xs text-gray-500 mb-1">植物类型</p>
                                                            <div className="flex flex-wrap gap-1">
                                                                {plant.types?.map((type, index) => (
                                                                    <span key={index} className="bg-gray-100 text-gray-800 text-xs px-2 py-0.5 rounded">
                                                                        {type}
                                                                    </span>
                                                                ))}
                                                            </div>
                                                        </div>

                                                        <div className="mb-4">
                                                            <p className="text-xs text-gray-500 mb-1">养护频率</p>
                                                            <p className="text-sm">{plant.care_frequency || '适中'}</p>
                                                        </div>

                                                        <button
                                                            onClick={() => {
                                                                setNewApplication({
                                                                    ...newApplication,
                                                                    plant_id: plant.id
                                                                });
                                                                setActiveTab('newApplication');
                                                            }}
                                                            className="w-full py-2 bg-green-600 text-white rounded-md hover:bg-green-700 text-sm"
                                                        >
                                                            申请认领
                                                        </button>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* 我的申请标签页 */}
                            {activeTab === 'applications' && (
                                <div>
                                    <div className="flex justify-between items-center mb-6">
                                        <h2 className="text-lg font-semibold">我的认领申请</h2>
                                        <button
                                            onClick={() => setActiveTab('newApplication')}
                                            className="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                                        >
                                            新申请
                                        </button>
                                    </div>

                                    {/* 状态筛选 */}
                                    <div className="flex flex-wrap gap-2 mb-6">
                                        <button
                                            onClick={() => setApplicationStatusFilter('all')}
                                            className={`px-3 py-1 rounded-full text-sm ${applicationStatusFilter === 'all'
                                                ? 'bg-green-100 text-green-800'
                                                : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                                                }`}
                                        >
                                            全部
                                        </button>
                                        <button
                                            onClick={() => setApplicationStatusFilter('pending')}
                                            className={`px-3 py-1 rounded-full text-sm ${applicationStatusFilter === 'pending'
                                                ? 'bg-yellow-100 text-yellow-800'
                                                : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                                                }`}
                                        >
                                            待审核
                                        </button>
                                        <button
                                            onClick={() => setApplicationStatusFilter('approved')}
                                            className={`px-3 py-1 rounded-full text-sm ${applicationStatusFilter === 'approved'
                                                ? 'bg-green-100 text-green-800'
                                                : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                                                }`}
                                        >
                                            已通过
                                        </button>
                                        <button
                                            onClick={() => setApplicationStatusFilter('rejected')}
                                            className={`px-3 py-1 rounded-full text-sm ${applicationStatusFilter === 'rejected'
                                                ? 'bg-red-100 text-red-800'
                                                : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                                                }`}
                                        >
                                            已拒绝
                                        </button>
                                        <button
                                            onClick={() => setApplicationStatusFilter('expired')}
                                            className={`px-3 py-1 rounded-full text-sm ${applicationStatusFilter === 'expired'
                                                ? 'bg-gray-100 text-gray-800'
                                                : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                                                }`}
                                        >
                                            已过期
                                        </button>
                                    </div>

                                    {filteredApplications.length === 0 ? (
                                        <div className="bg-white p-8 rounded-lg shadow text-center">
                                            <h3 className="text-lg font-medium text-gray-900 mb-2">暂无认领申请</h3>
                                            <p className="text-gray-500 mb-4">您还没有提交任何认领申请</p>
                                            <button
                                                onClick={() => setActiveTab('newApplication')}
                                                className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                                            >
                                                提交申请
                                            </button>
                                        </div>
                                    ) : (
                                        <div className="bg-white rounded-lg shadow overflow-hidden">
                                            <table className="min-w-full divide-y divide-gray-200">
                                                <thead className="bg-gray-50">
                                                    <tr>
                                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                            植物ID
                                                        </th>
                                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                            申请时间
                                                        </th>
                                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                            状态
                                                        </th>
                                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                            操作
                                                        </th>
                                                    </tr>
                                                </thead>
                                                <tbody className="bg-white divide-y divide-gray-200">
                                                    {filteredApplications.map((application) => (
                                                        <tr key={application.id}>
                                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                                {application.plant_id.slice(0, 8)}...
                                                            </td>
                                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                                {new Date(application.created_at).toLocaleString()}
                                                            </td>
                                                            <td className="px-6 py-4 whitespace-nowrap">
                                                                {getStatusBadge(application.status)}
                                                            </td>
                                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                                <button
                                                                    onClick={() => handleViewApplication(application.id)}
                                                                    className="text-blue-600 hover:text-blue-900 mr-3"
                                                                >
                                                                    查看
                                                                </button>
                                                                {application.status === 'pending' && (
                                                                    <button
                                                                        onClick={() => handleCancelApplication(application.id)}
                                                                        className="text-red-600 hover:text-red-900"
                                                                    >
                                                                        取消
                                                                    </button>
                                                                )}
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* 我的认领标签页 */}
                            {activeTab === 'myClaims' && (
                                <div>
                                    <h2 className="text-lg font-semibold mb-6">我的认领植物</h2>

                                    {plantClaims.length === 0 ? (
                                        <div className="bg-white p-8 rounded-lg shadow text-center">
                                            <h3 className="text-lg font-medium text-gray-900 mb-2">暂无认领植物</h3>
                                            <p className="text-gray-500 mb-4">您还没有成功认领任何植物</p>
                                            <button
                                                onClick={() => setActiveTab('recommendations')}
                                                className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                                            >
                                                浏览推荐
                                            </button>
                                        </div>
                                    ) : (
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            {plantClaims.map((claim) => (
                                                <div key={claim.plant_id} className="bg-white rounded-lg shadow overflow-hidden">
                                                    <div className="h-48 bg-gray-200 relative">
                                                        {/* 植物图片占位 */}
                                                        <div className="absolute inset-0 flex items-center justify-center">
                                                        </div>
                                                        <div className="absolute top-2 right-2 bg-green-600 text-white text-xs px-2 py-1 rounded">
                                                            已认领
                                                        </div>
                                                    </div>
                                                    <div className="p-4">
                                                        <h3 className="font-semibold text-lg mb-1">{claim.plant_name || `植物 ${claim.plant_id.slice(0, 8)}`}</h3>
                                                        <p className="text-sm text-gray-500 mb-3">
                                                            认领于 {new Date(claim.claimed_at).toLocaleDateString()}
                                                        </p>

                                                        <div className="mb-4">
                                                            <p className="text-sm font-medium mb-2">养护记录</p>
                                                            <textarea
                                                                value={careNotes || claim.care_notes || ''}
                                                                onChange={(e) => setCareNotes(e.target.value)}
                                                                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm"
                                                                rows="2"
                                                                placeholder="记录植物的生长情况和养护措施"
                                                            ></textarea>
                                                            <button
                                                                onClick={() => handleUpdateCareNotes(claim.plant_id)}
                                                                className="mt-2 px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700"
                                                            >
                                                                保存记录
                                                            </button>
                                                        </div>

                                                        {claim.collaborators && claim.collaborators.length > 0 && (
                                                            <div className="mb-4">
                                                                <p className="text-sm font-medium mb-1">协作人</p>
                                                                <div className="flex -space-x-2">
                                                                    {claim.collaborators.map((collaborator, index) => (
                                                                        <img
                                                                            key={index}
                                                                            src={defaultAvatar}
                                                                            alt="协作人头像"
                                                                            className="w-8 h-8 rounded-full border-2 border-white"
                                                                        />
                                                                    ))}
                                                                    <button className="w-8 h-8 rounded-full bg-gray-100 border-2 border-white flex items-center justify-center text-gray-500 text-xs">
                                                                        +
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        )}

                                                        <div className="flex space-x-2">
                                                            <button
                                                                className="flex-1 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 text-sm"
                                                            >
                                                                查看详情
                                                            </button>
                                                            <button
                                                                onClick={() => handleReleaseClaim(claim.plant_id)}
                                                                className="flex-1 py-2 border border-red-300 text-red-600 rounded-md hover:bg-red-50 text-sm"
                                                            >
                                                                释放认领
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* 偏好设置标签页 */}
                            {activeTab === 'preferences' && (
                                <div>
                                    <h2 className="text-lg font-semibold mb-6">认领偏好设置</h2>

                                    {showPreferenceForm ? (
                                        <PreferenceForm />
                                    ) : (
                                        <>
                                            {preferences ? (
                                                <div className="bg-white p-6 rounded-lg shadow-md">
                                                    <div className="flex justify-between items-center mb-6">
                                                        <p className="text-gray-500">这些偏好将用于为您推荐最合适的植物</p>
                                                        <button
                                                            onClick={() => setShowPreferenceForm(true)}
                                                            className="flex items-center px-3 py-1 border border-gray-300 rounded-md text-sm hover:bg-gray-50"
                                                        >
                                                            编辑
                                                        </button>
                                                    </div>

                                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                                        <div>
                                                            <h3 className="text-sm font-medium text-gray-700 mb-2">偏好植物类型</h3>
                                                            <div className="flex flex-wrap gap-2">
                                                                {preferences.preferred_plant_types.map((type, index) => (
                                                                    <span key={index} className="px-2 py-1 bg-gray-100 text-gray-800 rounded-full text-sm">
                                                                        {type}
                                                                    </span>
                                                                ))}
                                                            </div>
                                                        </div>

                                                        <div>
                                                            <h3 className="text-sm font-medium text-gray-700 mb-2">偏好位置</h3>
                                                            <div className="flex flex-wrap gap-2">
                                                                {preferences.preferred_locations.map((location, index) => (
                                                                    <span key={index} className="px-2 py-1 bg-gray-100 text-gray-800 rounded-full text-sm">
                                                                        {location}
                                                                    </span>
                                                                ))}
                                                            </div>
                                                        </div>

                                                        <div>
                                                            <h3 className="text-sm font-medium text-gray-700 mb-2">期望养护频率</h3>
                                                            <p>{preferences.care_frequency || '未设置'}</p>
                                                        </div>

                                                        <div>
                                                            <h3 className="text-sm font-medium text-gray-700 mb-2">最大认领数量</h3>
                                                            <p>{preferences.max_plants}</p>
                                                        </div>

                                                        <div>
                                                            <h3 className="text-sm font-medium text-gray-700 mb-2">通知偏好</h3>
                                                            <div className="space-y-1">
                                                                <div className="flex items-center">

                                                                    <span>邮件通知</span>
                                                                </div>
                                                                <div className="flex items-center">

                                                                    <span>推送通知</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            ) : (
                                                <div className="bg-white p-8 rounded-lg shadow text-center">
                                                    <h3 className="text-lg font-medium text-gray-900 mb-2">尚未设置认领偏好</h3>
                                                    <p className="text-gray-500 mb-4">设置您的偏好可以帮助我们为您推荐更合适的植物</p>
                                                    <button
                                                        onClick={() => setShowPreferenceForm(true)}
                                                        className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                                                    >
                                                        设置偏好
                                                    </button>
                                                </div>
                                            )}
                                        </>
                                    )}
                                </div>
                            )}

                            {/* 新申请标签页 */}
                            {activeTab === 'newApplication' && (
                                <div>
                                    <div className="flex items-center mb-6">
                                        <button
                                            onClick={() => setActiveTab('applications')}
                                            className="mr-2 text-gray-500 hover:text-gray-700"
                                        >
                                        </button>
                                        <h2 className="text-lg font-semibold">提交认领申请</h2>
                                    </div>

                                    <ApplicationForm />
                                </div>
                            )}

                            {/* 申请详情弹窗 */}
                            {showApplicationDetail && <ApplicationDetailModal />}
                        </>
                    )}
                </main>
            </div>
        </div>
    );
};

export default Claims;